# -*- coding: utf-8 -*-
# @File: backend => user_api.py
# @CreateTime: 2025/8/26 09:15
# @Author: EvanZhang
# @Info: 用户中心相关接口
from fastapi import APIRouter, HTTPException, Depends
from fastapi.responses import JSONResponse
from typing import List

from apps.crud.user_view import user_register, user_login, update_user_token, update_user_profile
from apps.models import User
from apps.schemas.user_schema import UserRegisterRequest, UserLoginRequest, Token, UserLoginResponse, \
    UserProfileRequest, UserBase
from apps.utils.jwt import verify_jwt_token

users = APIRouter(prefix='/user', tags=['用户中心'])

@users.post('/register', description='用户注册相关接口', summary='用户注册')
async def register(user:UserRegisterRequest):
    # try:
    #     existing_user = await User.get_or_none(username=user.username)
    #     if existing_user:
    #         raise HTTPException(status_code=400, detail="用户名已存在")
    #
    #
    #     new_user = await User.create(
    #         username=user.username,
    #         password_hash=user.password, # 密码传输前进行md5加密
    #     )
    #     return JSONResponse(content={"message": "注册成功, 请登录"})
    # except HTTPException:
    #     raise
    # except Exception as e:
    #     raise HTTPException(status_code=500, detail="注册失败, 请稍后再试") from e
    result = await user_register(user)
    if result == 201:
        return JSONResponse(content={"message": "注册成功, 请登录"})
    elif result == 400:
        raise HTTPException(status_code=400, detail="用户名已存在")
    else:
        raise HTTPException(status_code=500, detail="注册失败, 请稍后再试") from result

@users.post('/login', description='用户登录相关接口', summary='用户登录', response_model=UserLoginResponse)
async def login(user:UserLoginRequest):
    result = await user_login(user)
    if result[0] == 200:
        return result[1]
    elif result[0] == 400:
        raise HTTPException(status_code=result[0], detail=result[1])
    else:
        raise HTTPException(status_code=result[0], detail='登录失败:' + str(result[1]))

@users.get('/updatet',summary='更新用户Token,防止过期',response_model=Token)
async def update_token(user: UserBase = Depends(verify_jwt_token)):
    result = update_user_token(user)
    if result[0] == 200:
        return result[1]
    else:
        raise HTTPException(status_code=result[0], detail='更新Token失败:' + str(result[1]))

# 这个接口可能不需要开发,因为登录后会返回信息
# @users.get('/profile',summary='查看自己信息',response_model=UserLoginResponse)

@users.put('/profile',summary='更新自己信息')
async def update_profile(img: UserProfileRequest, user: UserBase = Depends(verify_jwt_token)):
    # 调接口
    result = await update_user_profile(user.username,img)
    if result[0] == 201:
        return JSONResponse(content={"message": "更新成功"})
    elif result[0] == 400:
        raise HTTPException(status_code=result[0], detail=result[1])
    else:
        raise HTTPException(status_code=result[0], detail='更新失败:' + str(result[1]))


